package org.linlinjava.litemall.admin.job;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.notify.NoticeHelper;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.LitemallCoupon;
import org.linlinjava.litemall.db.domain.LitemallCouponUser;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallCouponService;
import org.linlinjava.litemall.db.service.LitemallCouponUserService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.MonthDay;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 检测优惠券过期情况
 */
@Component
@RequiredArgsConstructor
public class CouponJob {
    private final Log logger = LogFactory.getLog(CouponJob.class);

    /**
     * 息服务
     */
    private final LitemallCouponService couponService;

    private final LitemallUserService litemallUserService;
    /**
     * 优惠券用户服务
     */
    private final LitemallCouponUserService couponUserService;
    private final NoticeHelper noticeHelper;

    /**
     * 每隔一个小时检查
     * TODO
     * 注意，因为是相隔一个小时检查，因此导致优惠券真正超时时间可能比设定时间延迟1个小时
     */
    //@Scheduled(fixedDelay = 1 * 60 * 1000)
    @Transactional
    public void checkCouponExpired() {
        logger.info("系统开启任务检查优惠券是否已经过期");

        List<LitemallCoupon> couponList = couponService.queryExpired();
        for (LitemallCoupon coupon : couponList) {
            coupon.setStatus(Constants.COUPON_STATUS_EXPIRED);
            couponService.updateById(coupon);
        }

        List<LitemallCouponUser> couponUserList = couponUserService.queryExpired();
        for (LitemallCouponUser couponUser : couponUserList) {
            couponUser.setStatus(Constants.COUPON_STATUS_EXPIRED);
            couponUserService.update(couponUser);
        }
    }

   // @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void checkCouponBirthday(){
        logger.info("系统开启任务检查生日优惠券发放");
        //是否有电子优惠券 生日福利券 且已上架 (只能设置一张)
        List<LitemallCoupon> couponList = couponService.queryAll(1);
        List<LitemallCoupon> birthdayCoupon=couponList.stream().filter(coupon -> coupon.getStatus() == 1&&coupon.getIsBirthdayUse()==1).collect(Collectors.toList());
        if(CollUtil.isEmpty(couponList)){return;}
        //获取当天所有过生日的用户
        List<LitemallUser> litemallUserList = litemallUserService.list(Wrappers.lambdaQuery(LitemallUser.class).isNotNull(LitemallUser::getBirthday));
        LocalDate currentDate = LocalDate.now();
        List<LitemallUser> birthdayUser = litemallUserList.stream().filter(litemallUser -> {
            MonthDay monthDay = MonthDay.from(litemallUser.getBirthday());
            MonthDay nowMonthDay = MonthDay.from(currentDate);
            return monthDay.equals(nowMonthDay);
        }).collect(Collectors.toList());
        if(CollUtil.isEmpty(litemallUserList)){return;}
        CompletableFuture.runAsync(()->{
            //发放优惠券 所有是生日福利的券
            for (LitemallUser litemallUser : birthdayUser) {
                for (LitemallCoupon litemallCoupon : birthdayCoupon) {
                    //无限数量发放
                    if(litemallCoupon.getTotal()==0){
                        LitemallCouponUser litemallCouponUser =new LitemallCouponUser();
                        litemallCouponUser.setUserId(litemallUser.getId());
                        litemallCouponUser.setCouponId(litemallCoupon.getId());
                        litemallCouponUser.setStatus((short) 0);
                        litemallCouponUser.setStartTime(litemallCoupon.getStartTime()!=null?litemallCoupon.getStartTime():LocalDateTime.now());
                        litemallCouponUser.setEndTime(litemallCoupon.getEndTime()!=null?litemallCoupon.getEndTime():LocalDateTime.now().plusDays(litemallCoupon.getDays()));
                        litemallCouponUser.setDeleted(false);
                        couponUserService.add(litemallCouponUser);
                        //发放福利券消息
                        noticeHelper.noticeUser( Constants.MSG_TYPE_OTHER,"Happy birthday","Happy birthday, "+litemallUser.getNickname()+"! You have received a coupon for your birthday !Please go to the coupons page for details !",litemallUser.getId(),litemallCoupon);
                    }else
                    //有限数量发放
                    if (litemallCoupon.getTotal()!=0&&couponUserService.countCoupon(litemallCoupon.getId())<=litemallCoupon.getTotal()){
                        LitemallCouponUser litemallCouponUser =new LitemallCouponUser();
                        litemallCouponUser.setUserId(litemallUser.getId());
                        litemallCouponUser.setCouponId(litemallCoupon.getId());
                        litemallCouponUser.setStatus((short) 0);
                        litemallCouponUser.setStartTime(litemallCoupon.getStartTime()!=null?litemallCoupon.getStartTime():LocalDateTime.now());
                        litemallCouponUser.setEndTime(litemallCoupon.getEndTime()!=null?litemallCoupon.getEndTime():LocalDateTime.now().plusDays(litemallCoupon.getDays()));
                        litemallCouponUser.setDeleted(false);
                        couponUserService.add(litemallCouponUser);
                        //发放福利券消息
                        noticeHelper.noticeUser( Constants.MSG_TYPE_OTHER,"Happy birthday","Happy birthday, "+litemallUser.getNickname()+"! You have received a coupon for your birthday !Please go to the coupons page for details !",litemallUser.getId(),litemallCoupon);
                    }
                }
            }
        });
    }


}
